import axios from 'axios'
import { MessageBox, Message, Loading } from 'element-ui'
import store from '@/store'
import { getToken, getUserInfo } from '@/utils/auth'
import { blobDownload } from '@/utils'

const loadingInstance = null

const defaultRequestOption = {
  isAutoParse: true
}

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true,
  timeout: 15000
})

service.interceptors.request.use(
  config => {
    // loadingInstance = Loading.service({ lock: true })

    const { orgId, id } = getUserInfo()
    config.headers['token'] = getToken()
    config.headers['orgId'] = orgId
    config.headers['accountId'] = id
    if (config.type === 'form') {
      config.headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'
    } else {
      config.headers['Content-Type'] = 'application/json;charset=UTF-8'
    }
    return config
  },
  error => {
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

service.interceptors.response.use(

  response => {
    // loadingInstance.close()
    const option = { ...defaultRequestOption, ...response.config }
    const res = response.data

    if (option.onlyFile) {
      if (!res.size) {
        Message({
          message: '导出的数据为空!',
          type: 'warning',
          duration: 1500
        })
        return false
      }
      blobDownload(res, response.headers)
      return false
    }

    if (response.status === 401) {
      MessageBox.confirm('您已注销，您可以取消以停留在此页，或重新登录', '确认注销', {
        confirmButtonText: '重新登录',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        store.dispatch('user/resetToken').then(() => {
          location.reload()
        })
      }).catch(() => {
        return Promise.reject(new Error(res.message || 'Error'))
      })
    }
    if (response.status !== 200) {
      return Promise.reject(new Error(res.message || 'Error'))
    }

    if (!option.isAutoParse) {
      return res
    }

    if (res.code !== 0) {
      Message({
        message: res.message || 'Error',
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res.data
    }
  },
  error => {
    // loadingInstance.close()
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
